package com.doform.android.xianggucheng.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.doform.android.xianggucheng.R;
import com.doform.android.xianggucheng.adapter.CommonListAdapter;
import com.doform.android.xianggucheng.bean.CategoryQueryBean;
import com.doform.android.xianggucheng.bean.CommonQueryBean;
import com.doform.android.xianggucheng.bean.GuidBean;
import com.doform.android.xianggucheng.bean.ImageBean;
import com.doform.android.xianggucheng.bean.UnitBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqAddArtcle;
import com.doform.android.xianggucheng.bean.request_bean.ReqImage;
import com.doform.android.xianggucheng.bean.request_bean.ReqListMeasureUnitBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqQueryCategory;
import com.doform.android.xianggucheng.bean.request_bean.ReqQueryVendorBean2;
import com.doform.android.xianggucheng.holder.ViewHolder;
import com.doform.android.xianggucheng.popwindow.CommonPopWindow;
import com.doform.android.xianggucheng.popwindow.IPopWindow;
import com.doform.android.xianggucheng.retrofit.ApiSpecTransformer.DialogTransformer;
import com.doform.android.xianggucheng.retrofit.HttpManager;
import com.doform.android.xianggucheng.retrofit.subscriber.ErrorHandleSubscriber;
import com.doform.android.xianggucheng.utils.BitMapUtil;
import com.doform.android.xianggucheng.utils.KeyBoardUtils;
import com.doform.android.xianggucheng.utils.TsUtils;
import com.doform.android.xianggucheng.widget.DIYScrollView;
import com.doform.android.xianggucheng.widget.DividerItemDecoration;
import com.doform.android.xianggucheng.widget.ScrollViewListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.iwf.photopicker.PhotoPicker;

import static com.doform.android.xianggucheng.R.id.tv;


/**
 * Created by Administrator on 2017/5/12.
 */

public class NewGoodsActivity extends BaseTitleActivity {

    @BindView(R.id.tv_vendor)
    TextView mVendor;//供应商

    @BindView(R.id.tv_category)
    TextView tv_category;

    @BindView(R.id.et_name)
    EditText et_name;//商品名称

    @BindView(R.id.tv_module)
    TextView mModule;//计量单位

    @BindView(R.id.et_cost_price)
    EditText et_cost_price;//成本价

    @BindView(R.id.et_retail_price)
    EditText et_retail_price;//零售价

    @BindView(R.id.tv_state)
    TextView tvState;//状态

    @BindView(R.id.ll)
    LinearLayout mLl;

    @BindView(R.id.rl_state)
    RelativeLayout rl_state;

    @BindView(R.id.scrollView)
    DIYScrollView mScrollView;
    /**
     * select Picture
     */

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;

    private String mVendorId;//供应商ID
    private String mCategoryId;//分类ID
    private String mCategoryName;//分类名称
    private String mName;//商品名称
    private String mCostPrice;//成本价
    //    private String mRetailPrice;//零售价
    private String mMessureId;//计量单位
    private String mMessureName;//计量
    private String mArticleState;//商品状态

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    private List<CommonQueryBean> vendorDatas = new ArrayList<>();
    private List<CategoryQueryBean> mCategoryDatas = new ArrayList<>();
    private List<UnitBean.DataBean> mUnitDatas = new ArrayList<>();

    private IPopWindow mPopupWindow, mPopupWindow4, mPopupWindow5;
    private CommonPopWindow mPopupWindow2;
    private RecyclerView mCategoryRecyclerView;
    private ArrayList<String> photos = new ArrayList<>();
    private CommonAdapter<String> photoAdapter;
    private String mRetailPrice;


    @Override
    protected int layoutResId() {
        return R.layout.activity_new_and_update_goods;
    }

    @Override
    protected void init() {
        if (mPopupWindow == null) {
            mPopupWindow = new IPopWindow(this, R.layout.pop_new_add_goodsk);
        }

        if (mPopupWindow2 == null) {
            mPopupWindow2 = new CommonPopWindow(this, R.layout.pop_goods_category);
        }

        if (mPopupWindow4 == null) {
            mPopupWindow4 = new IPopWindow(this, R.layout.pop_new_add_goodsk);
        }
        if (mPopupWindow5 == null) {
            mPopupWindow5 = new IPopWindow(this, R.layout.pop_new_add_goodsk);
        }
    }

    @Override
    protected void initView() {

        mCategoryRecyclerView = mPopupWindow2.getView(R.id.recyclerView);
        mCategoryRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mCategoryRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mCategoryRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());

        tvState.setText("上架");
        mArticleState = "1";

    }

    @Override
    protected void initData() {
        initVendorData();
        initCategoryData();
        initMeasureData();
    }

    @Override
    protected void initListener() {

        mScrollView.setScrollViewListener(new ScrollViewListener() {
            @Override
            public void onScrollChanged(DIYScrollView scrollView, int x, int y, int oldx, int oldy) {
                KeyBoardUtils.closeKeybord(et_name, NewGoodsActivity.this);
            }
        });

        photoAdapter = new CommonAdapter<String>(this, R.layout.item_photos, photos) {
            @Override
            protected void convert(com.zhy.adapter.recyclerview.base.ViewHolder holder, String s, final int position) {
                ImageView iv = holder.getView(R.id.iv);
                Glide.with(NewGoodsActivity.this).load(new File(s)).into(iv);
                CardView cv = holder.getView(R.id.card_view);
                cv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(NewGoodsActivity.this);
                        builder.setTitle("删除对话框");
                        builder.setMessage("确认不上传该图片？");
                        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                photos.remove(position);
                                notifyDataSetChanged();
                                dialog.dismiss();
                            }
                        });
                        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        builder.create().show();
                    }
                });
            }
        };
        mRecyclerView.setAdapter(photoAdapter);

    }

    @Override
    protected void showView() {
        titleBar.setTextTitle("新增商品");
    }

    @OnClick({R.id.tv_vendor, R.id.tv_module, R.id.btn_submit, R.id.tv_category, R.id.btn_select_pic, R.id.tv_state})
    protected void processClick(View v) {
        switch (v.getId()) {
            case R.id.tv_vendor:
                showVendorPop(vendorDatas);
                break;
            case R.id.tv_category:
                showCategoryPop(mCategoryDatas);
                break;
            case R.id.tv_module:
                showMeasurePop(mUnitDatas);
                break;
            case R.id.btn_submit:
                beforeSubmit();
                break;
            case R.id.btn_select_pic:
                getPickPhoto();
                break;
            case R.id.tv_state:
                showSatePop();
                break;
            default:
                break;
        }
    }

    private void showSatePop() {
        List<String> states = new ArrayList<>();
        states.add("下架");
        states.add("上架");
        mPopupWindow5.setPopAdapter(new CommonListAdapter<String>(this, states, R.layout.pop_item) {
            @Override
            protected void convert(ViewHolder vh, final List<String> datas, final int position) {

                TextView tv = vh.getView(R.id.tv);
                tv.setText(datas.get(position));
                vh.getView(R.id.rl_select).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tvState.setText(datas.get(position));
                        if ("下架".equals(tvState.getText().toString())) {
                            mArticleState = "0";
                        } else {
                            mArticleState = "1";
                        }
                        mPopupWindow5.dismiss();
                    }
                });
            }
        });
        mPopupWindow5.showAtLocation(mLl, Gravity.BOTTOM, 0, 0);
    }

    private void getPickPhoto() {
        PhotoPicker.builder()
                .setPhotoCount(6)
                .setShowCamera(true)
                .setShowGif(true)
                .setPreviewEnabled(true)
                .start(this, PhotoPicker.REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                ArrayList<String> tempList = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                if (tempList.size() != 0) {
                    photos.clear();
                    photos.addAll(tempList);
                    photoAdapter.notifyDataSetChanged();
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void beforeSubmit() {

        mName = et_name.getText().toString().trim();
        mCostPrice = et_cost_price.getText().toString().trim();
        mRetailPrice = et_retail_price.getText().toString().trim();

        if (TextUtils.isEmpty(mName)) {
            Toast.makeText(this, "请填写商品名称", Toast.LENGTH_SHORT).show();
            return;
        } else if (TextUtils.isEmpty(mCostPrice)) {
            Toast.makeText(this, "请填写商品成本价格", Toast.LENGTH_SHORT).show();
            return;
        } else if (TextUtils.isEmpty(mRetailPrice)) {
            Toast.makeText(this, "请填写商品销售价格", Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(mVendorId)) {
            Toast.makeText(this, "请填写供应商", Toast.LENGTH_SHORT).show();
            return;
        } else if (TextUtils.isEmpty(mCategoryId)) {
            Toast.makeText(this, "请选择分类", Toast.LENGTH_SHORT).show();
            return;
        } else if (TextUtils.isEmpty(mMessureId)) {
            Toast.makeText(this, "请选择计量单位", Toast.LENGTH_SHORT).show();
            return;
        }
        if (photos.size() == 0) {// 大神
            postDataToService(mName, mCategoryId, mVendorId, mCostPrice, mRetailPrice, mMessureId, mMessureName, "", "", mArticleState)
                    .subscribe(new SubmitResultSubscriber());
        } else {
            postBase64Bitmap();
        }

    }


    private void postBase64Bitmap() {

        Observable.just(photos)
                .subscribeOn(Schedulers.io())
                .map(new Function<ArrayList<String>, String[]>() {
                         @Override
                         public String[] apply(@NonNull ArrayList<String> strings) throws Exception {
                             String imgType = "";
                             String[] strArray = new String[strings.size()];
                             for (int i = 0; i < strings.size(); i++) {
                                 if (strings.get(i).endsWith(".jpg")) {
                                     imgType = "jpg";
                                 } else if (strings.get(i).endsWith(".png")) {
                                     imgType = "png";
                                 } else if (strings.get(i).endsWith(".gif")) {
                                     imgType = "gif";
                                 } else {
                                     TsUtils.showToast("请选择png/jpg/gif格式的图片");
                                 }
                                 strArray[i] = BitMapUtil.imgCompress(strings.get(i), 480, 800, 100, imgType);
                             }
                             return strArray;
                         }
                     }
                )
                .map(new Function<String[], String>() {
                         @Override
                         public String apply(@NonNull String[] strings) throws Exception {
                             return JSON.toJSONString(strings);
                         }
                     }
                )
                .flatMap(new Function<String, ObservableSource<ArrayList<ImageBean>>>() {
                             @Override
                             public ObservableSource<ArrayList<ImageBean>> apply(@NonNull String json) throws Exception {
                                 return HttpManager.instance()
                                         .postImg(new ReqImage(json));
                             }
                         }
                )
                .flatMap(new Function<ArrayList<ImageBean>, ObservableSource<GuidBean>>() {
                             @Override
                             public ObservableSource<GuidBean> apply(@NonNull ArrayList<ImageBean> data) throws Exception {

                                 String imgId = "";
                                 String imgFilesName = "";
                                 for (int i = 0; i < data.size(); i++) {
                                     if (i == data.size() - 1) {
                                         imgId = imgId + data.get(i).getId();
                                         imgFilesName = imgFilesName + data.get(i).getUrl();
                                     } else {
                                         imgId = imgId + data.get(i).getId() + ",";
                                         imgFilesName = imgFilesName + data.get(i).getUrl() + ",";
                                     }
                                 }
                                 return postDataToService(mName, mCategoryId, mVendorId, mCostPrice, mRetailPrice,
                                         mMessureId, mMessureName, imgId, imgFilesName,mArticleState);
                             }
                         }
                )
                .compose(new DialogTransformer<GuidBean>(mProgressBar))
                .subscribe(new SubmitResultSubscriber());
    }

    private Observable<GuidBean> postDataToService(String mName, String mCategoryFId, String mVendorId, String mCostPrice,
                                                   String mRetailPrice, String mMessureId, String mMessureName,
                                                   String img, String imgFile, String mArticleState) {
        return HttpManager.instance()
                .addArtcle(new ReqAddArtcle(mName, mCategoryFId, mVendorId, mCostPrice, mRetailPrice, mMessureId, mMessureName, img, imgFile,mArticleState));
    }

    public void showVendorPop(List<CommonQueryBean> datas) {

        mPopupWindow.setHeadName("添加供应商");

        mPopupWindow.setHeadListener(new View.OnClickListener() {
                                         @Override
                                         public void onClick(View v) {
                                             startActivity(new Intent(NewGoodsActivity.this, NewVendorActivity.class));
                                         }
                                     }
        );
        mPopupWindow.setPopAdapter(new CommonListAdapter<CommonQueryBean>(this, datas, R.layout.pop_item) {
                                       @Override
                                       protected void convert(ViewHolder vh, final List<CommonQueryBean> datas, final int position) {
                                           final CommonQueryBean dataBean = datas.get(position);

                                           TextView tvVendor = vh.getView(tv);
                                           tvVendor.setText(dataBean.getName());
                                           vh.getView(R.id.rl_select).setOnClickListener(new View.OnClickListener() {
                                                                                             @Override
                                                                                             public void onClick(View v) {
                                                                                                 mVendor.setText(dataBean.getName());
                                                                                                 mVendorId = dataBean.getId();
                                                                                                 mPopupWindow.dismiss();
                                                                                             }
                                                                                         }
                                           );
                                       }
                                   }
        );
        mPopupWindow.showAtLocation(mLl, Gravity.BOTTOM, 0, 0);
    }


    public void showCategoryPop(final List<CategoryQueryBean> datas) {
        CommonAdapter mCategoryItemCateAdapter = new CommonAdapter<CategoryQueryBean>(this, R.layout.pop_category_item2, datas) {
            @Override
            protected void convert(com.zhy.adapter.recyclerview.base.ViewHolder holder, CategoryQueryBean listBean, int position) {
                TextView tv_name = holder.getView(R.id.tv);
                TextView tv_name2 = holder.getView(R.id.tv2);
                if (listBean.getLv() == 2) {//二级
                    tv_name2.setText(listBean.getName());
                } else if (listBean.getLv() == 1) {
                    tv_name.setText(listBean.getName());
                } else {
                }
            }
        };

        mCategoryItemCateAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                CategoryQueryBean bean = datas.get(position);
                mCategoryId = "";
                if (bean.getLv() == 1) {
                    mCategoryId = bean.getId();
                } else if (bean.getLv() == 2) {
                    mCategoryId = bean.getFid() + "," + bean.getId();
                } else {
                }
                mCategoryName = bean.getName();
                tv_category.setText(mCategoryName);
                mPopupWindow2.dismiss();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        mCategoryRecyclerView.setAdapter(mCategoryItemCateAdapter);
//
        mPopupWindow2.showAtLocation(mLl, Gravity.BOTTOM, 0, 0);
    }

    public void showMeasurePop(List<UnitBean.DataBean> datas) {
        mPopupWindow4.setGoneHeadView();
        mPopupWindow4.setPopAdapter(new CommonListAdapter<UnitBean.DataBean>(this, datas, R.layout.pop_item) {
            @Override
            protected void convert(ViewHolder vh, final List<UnitBean.DataBean> datas, final int position) {

                final UnitBean.DataBean messBean = datas.get(position);

                TextView tv = vh.getView(R.id.tv);
                tv.setText(messBean.getName());
                vh.getView(R.id.rl_select).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mModule.setText(messBean.getName());
                        mMessureId = messBean.getId();
                        mMessureName = messBean.getName();
                        mPopupWindow4.dismiss();
                    }
                });
            }
        });
        mPopupWindow4.showAtLocation(mLl, Gravity.BOTTOM, 0, 0);
    }

    /**
     * 计量单位列表
     */
    private void initMeasureData() {
        HttpManager.instance()
                .getMeasureUnit(new ReqListMeasureUnitBean("1"))
                .subscribe(new ErrorHandleSubscriber<UnitBean>() {
                               @Override
                               public void onNext(@NonNull UnitBean unitBean) {
                                   mUnitDatas.clear();
                                   mUnitDatas.addAll(unitBean.getList());
                               }
                           }
                );
    }


    /**
     * 分类数据
     */
    private void initCategoryData() {
        HttpManager.instance()
                .getCategoryQuery2(new ReqQueryCategory())
                .subscribe(new ErrorHandleSubscriber<ArrayList<CategoryQueryBean>>() {
                    @Override
                    public void onNext(@NonNull ArrayList<CategoryQueryBean> categoryBean) {
                        mCategoryDatas.addAll(categoryBean);
                    }
                });
    }

    /**
     * 供应商数据
     */
    private void initVendorData() {
        HttpManager
                .instance()
                .getVendorQuery2(new ReqQueryVendorBean2())
                .subscribe(new ErrorHandleSubscriber<ArrayList<CommonQueryBean>>() {
                               @Override
                               public void onNext(@NonNull ArrayList<CommonQueryBean> vendorBean) {
                                   vendorDatas.addAll(vendorBean);
                               }
                           }
                );
    }


}
